<!--
 * @Author: Liz.Zheng
 * @Date: 2021-12-01 16:51:33
 * @LastEditTime: 2023-02-15 11:19:03
 * @LastEditors: 郑亚莉 zhengyali@shequ.life
 * @Description: 房源管理
 * @Motto: Write the code. Change the world.
-->
<template>
  <div style="padding: 10px">
    <a-tabs v-model:activeKey="activeKey" style="margin-bottom: 16px">
      <a-tab-pane v-for="tab of tabList" :key="tab.key" :tab="tab.title" />
    </a-tabs>
    <!-- <a-card> -->
    <a-row type="flex" justify="space-between">
      <a-col :span="12">
        <a-input-search
          style="width: 200px"
          v-model:value="keywordsValue"
          placeholder="查询房号"
          @search="onSearch"
          :class="$store.getters.isMobile ? 'input-width' : 'input-class'"
        >
        </a-input-search>
        <a-select
          style="width: 200px; margin-left: 10px"
          placeholder="请选择房源标签"
          v-model:value="filterTagId"
          @change="gethouseList()"
          :allowClear="true"
          :options="optionsTag"
        />
      </a-col>
      <a-col :span="12" type="flex" style="text-align: end">
        <a-space>
          <a-button
            @click="btnExport"
            v-if="!$store.getters.isMobile && houseList.length > 0"
          >
            <DownloadOutlined />
            批量导出
          </a-button>
          <a-button @click="btnImport" v-if="!$store.getters.isMobile">
            <UploadOutlined />
            批量导入
          </a-button>
          <a-button type="primary" @click="buildingEdit()">
            <template #icon>
              <HomeOutlined />
            </template>
            新增{{ $L("房源") }}
          </a-button>
        </a-space>
        <!-- <a-button class="mr-10">
            <template #icon>
              <AppstoreAddOutlined />
            </template>
          </a-button> -->
      </a-col>
    </a-row>
    <!-- </a-card> -->
    <!-- <a-card>
      <template v-for="(tag, index) in tags" :key="tag">
        <a-tag :closable="index !== -1" @close="handleClose(tag)">
          {{ tag }}
        </a-tag>
      </template>
      <a-button type="text" style="color: #2681f3">清空选项</a-button>
    </a-card> -->
    <a-table
      style="margin-top: 10px"
      :columns="columns"
      rowKey="id"
      :dataSource="houseList"
      @change="handleTableChange"
      :customRow="Rowclick"
      :pagination="pagination"
      :scroll="{ x: 'max-content', y: $store.getters.isMobile ? 550 : true }"
      :loading="loading"
      sticky
    >
      <template #bodyCell="{ text, record, index, column }">
        <template v-if="column.key === 'tags'">
          <span>
            <TagList :list="record.tag_arr" :type="2" />
          </span>
        </template>
        <template v-if="column.key === 'invitation_status'">
          <a-tag v-if="text == 1" color="#108ee9"> 招商 </a-tag>
          <a-tag color="orange" v-else>不招商</a-tag>
        </template>
      </template>
      <template
        #customFilterDropdown="{
          setSelectedKeys,
          selectedKeys,
          confirm,
          clearFilters,
          column,
        }"
      >
        <div style="padding: 8px">
          <!-- <a-input
            ref="searchInput"
            placeholder="请搜索房源标签"
            :value="selectedKeys[0]"
            style="width: 188px; margin-bottom: 8px; display: block"
            @change="
              (e) => setSelectedKeys(e.target.value ? [e.target.value] : [])
            "
            @pressEnter="handleSearch(selectedKeys, confirm, column.dataIndex)"
          /> -->
          <a-select
            v-model:value="selectTagValue"
            show-search
            style="width: 200px; margin-bottom: 10px"
            optionFilterProp="label"
            :placeholder="placeholderTag"
            :options="optionsTag"
            allowClear
          />
          <div>
            <a-button
              type="primary"
              size="small"
              style="width: 90px; margin-right: 8px"
              @click="handleSearch(selectedKeys, confirm, column.dataIndex)"
            >
              <template #icon><SearchOutlined /></template>
              搜索
            </a-button>
            <a-button
              size="small"
              style="width: 90px"
              @click="handleReset(clearFilters)"
            >
              取消
            </a-button>
          </div>
        </div>
      </template>
      <template #customFilterIcon="{ filtered, column }">
        <template
          v-if="column.key === 'village_name' || column.key === 'build_name'"
        >
          <FilterFilled />
        </template>
        <template v-else>
          <SearchOutlined
            :style="{ color: filtered ? '#108ee9' : undefined }"
          />
        </template>
      </template>
    </a-table>
    <add-house
      v-if="buildingEditVisible"
      :visible="buildingEditVisible"
      :id="currentBuildingId"
      :villageId="currentBuildingVillageId"
      @cancel="handleBuildingClose"
      @success="handleBuildingSuccess"
    ></add-house>
    <RoomDrawer
      v-if="houseResourceVisible"
      :visible="houseResourceVisible"
      @cancel="houseResourceSuccess"
      :detail="roomDetail"
      pageFrom="HouseResource"
    />
    <!-- 导入房源 -->
    <import :visible="visibleImport" @refresh="refreshList" @clear="btnClear" />
  </div>
</template>

<script>
import {
  defineComponent,
  ref,
  computed,
  reactive,
  toRefs,
  watch,
  // nextTick
} from "vue";
import {
  HomeOutlined,
  UploadOutlined,
  SearchOutlined,
  DownloadOutlined,
  FilterFilled,
} from "@ant-design/icons-vue";
import request from "../../../common/utils/request";
import AddHouse from "./modules/AddHouse.vue";
import RoomDrawer from "../../../components/village/RoomDrawer.vue";
import store from "../../../store";
import TagList from "../../../components/Tag/show.vue";
import Import from "./modules/Import.vue";
import BLCOMMON from "bl-common-vue3";
import _ from "lodash";
import { Modal, message } from "ant-design-vue";
export default defineComponent({
  name: "houseResources",
  components: {
    HomeOutlined,
    SearchOutlined,
    AddHouse,
    RoomDrawer,
    TagList,
    Import,
    UploadOutlined,
    DownloadOutlined,
    FilterFilled,
  },
  setup() {
    const columns = computed(() => {
      return [
        {
          title: BLCOMMON.utils.L("项目名称"),
          dataIndex: "village_name",
          key: "village_name",
          fixed: store.getters.isMobile ? undefined : "left",
          filters:
            state.projectList && state.projectList.length
              ? state.projectList.map((item) => ({
                  value: item.id,
                  text: item.name,
                }))
              : [],
          filteredValue: filtersList.value?.village_name || [],
          width: 130,
        },
        {
          title: BLCOMMON.utils.L("楼宇名称"),
          dataIndex: "build_name",
          key: "build_name",
          filters:
            state.buildList && state.buildList.length
              ? state.buildList.map((item) => ({
                  value: item.id,
                  text: item.build_name,
                }))
              : [],
          filteredValue: filtersList.value?.build_name || [],
          width: 130,
        },
        {
          title: "楼层",
          dataIndex: "layer_name",
          width: 130,
        },
        {
          title: "房号",
          dataIndex: "room_name",
          width: 130,
        },
        {
          title: BLCOMMON.utils.L("计租面积"),
          dataIndex: "rental_area",
          width: 130,
        },
        {
          title: BLCOMMON.utils.L("报价"),
          dataIndex: "pre_unit_price_txt",
          width: 130,
        },
        {
          title: "租赁状态",
          dataIndex: "room_status_txt",
          width: 130,
        },
        {
          title: "可租日期",
          dataIndex: "lease_end",
          width: 130,
        },
        {
          title: BLCOMMON.utils.L("房源") + "标签",
          dataIndex: "tag_arr",
          key: "tags",
          width: 250,
        },
        {
          title: "虚拟" + BLCOMMON.utils.L("房源"),
          dataIndex: "is_unreal",
          key: "is_unreal",
          width: 100,
          customRender: ({ text }) => {
            return text == 1 ? "是" : "否";
          },
        },
        {
          title: "招商状态",
          dataIndex: "invitation_status",
          key: "invitation_status",
          width: 130,
        },
        {
          title: "装修情况",
          dataIndex: "decoration_txt",
          width: 100,
        },
        {
          title: "房源交付时间",
          dataIndex: "deliver_time",
          width: 130,
          customRender: ({ record }) => {
            return record.deliver_time && record.deliver_time.length > 10
              ? record.deliver_time.slice(0, 10)
              : " - ";
          },
        },
        {
          title: "创建时间",
          dataIndex: "created_at",
          width: 130,
          customRender: ({ record }) => {
            return record.created_at && record.created_at.length > 10
              ? record.created_at.slice(0, 10)
              : " - ";
          },
        },
      ];
    });

    const getBuildListByVillage = (list) => {
      let checkedBuild = [];
      list.forEach((village) => {
        if (village?.buildList?.length) {
          village.buildList.forEach((build) => {
            checkedBuild.push(build);
          });
        }
      });
      state.buildList = checkedBuild;
    };
    const screenList = () => {
      request
        .get("/org", "/build/villageAndBuildList", { checked: 1 })
        .then((res) => {
          state.projectList = res.villageList;
          getBuildListByVillage(state.projectList);
        });
    };
    screenList();

    //搜索词
    const keywordsValue = ref("");

    // 处理标签
    const state = reactive({
      tags: ["tag1", "Tag 2", "Tag3"],
      tabList: [
        {
          key: "all",
          title: "全部房源",
        },
        {
          key: "invitation",
          title: "招商房源",
        },
      ],
      activeKey: "all",
      filterTagId: undefined,
      projectList: [], // 项目筛选
      buildList: [], // 楼宇筛选
    });
    const handleClose = (removedTag) => {
      const tags = state.tags.filter((tag) => tag !== removedTag);
      console.log(tags);
      state.tags = tags;
    };
    // 渲染表格
    // 分页
    const page = ref(1);
    const limit = ref(20);
    const total = ref(0);
    const pagination = computed(() => ({
      total: total.value,
      current: page.value,
      pageSize: limit.value,
      showSizeChanger: true,
    }));
    const loading = ref(false);
    const filtersList = ref({});

    const handleTableChange = (pager, filters, sorter) => {
      console.log("pager, filters, sorter", pager, filters, sorter);
      page.value = pager.current;
      limit.value = pager.pageSize;

      let result = [];
      if (filters.village_name && filters.village_name.length > 0) {
        state.projectList.forEach((village) => {
          if (filters.village_name.includes(village.id)) {
            if (village.buildList && village.buildList.length > 0) {
              village.buildList.forEach((build) => {
                result.push(build);
              });
            }
          }
        });
      } else {
        state.projectList.forEach((village) => {
          if (village.buildList && village.buildList.length > 0) {
            village.buildList.forEach((build) => {
              result.push(build);
            });
          }
        });
      }
      state.buildList = result;
      if (filters?.build_name?.length) {
        let _build = filters.build_name.filter((v) => state.buildList.find((item) => item.id == v))
        filters.build_name = _build;
      }
      filtersList.value = filters;
      gethouseList();
    };

    // 请求房源列表
    const statisticData = ref({});
    const houseList = ref([]);

    const gethouseList = () => {
      loading.value = true;
      let params = {
        page: page.value,
        pageSize: limit.value,
        build_id:
          filtersList.value.build_name && filtersList.value.build_name.length
            ? filtersList.value.build_name.join(",")
            : undefined,
        village_id:
          filtersList.value.village_name &&
          filtersList.value.village_name.length
            ? filtersList.value.village_name.join(",")
            : undefined,
        keywords: keywordsValue.value || undefined,
        invitation_status: state.activeKey == "invitation" ? 1 : undefined,
        tag_id: state.filterTagId,
      };

      request
        .get("/village", "/houseResource/resourceList", params)
        .then((res) => {
          statisticData.value = res.countData;
          houseList.value = res.list;
          total.value = res.total;
          loading.value = false;
        });
    };
    watch(
      () => state.activeKey,
      () => {
        keywordsValue.value = "";
        state.filterTagId = undefined;
        filtersList.value = {};
        page.value = 1;
        limit.value = 20;
        gethouseList();
      }
    );
    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        console.log(
          `selectedRowKeys: ${selectedRowKeys}`,
          "selectedRows: ",
          selectedRows
        );
      },
      getCheckboxProps: (record) => ({
        disabled: record.name === "Disabled User",
        // Column configuration not to be checked
        name: record.name,
      }),
      onclick: (record) => {
        houseDetails(record);
      },
    };
    // 新增房源
    const buildingEditVisible = ref(false);
    const buildingEdit = () => {
      currentBuildingId.value = "";
      currentBuildingVillageId.value = "";
      buildingEditVisible.value = true;
    };
    const handleBuildingClose = () => {
      buildingEditVisible.value = false;
    };
    const handleBuildingSuccess = () => {
      init();
      handleBuildingClose();
    };
    // 房源信息

    const houseResourceVisible = ref(false);
    const roomDetail = ref({});
    const houseDetails = (record) => {
      roomDetail.value = record;
      houseResourceVisible.value = true;
    };
    const houseResourceClose = () => {
      houseResourceVisible.value = false;
      gethouseList();
    };

    const houseResourceSuccess = () => {
      houseResourceVisible.value = false;
      clearList();
    };
    const clearList = () => {
      houseResourceVisible.value = false;
      getTagList();
      gethouseList();
    };
    // 点击行
    const currentBuildingId = ref(0);
    const currentBuildingVillageId = ref(0);
    const currentBuildingroomId = ref(0);
    const Rowclick = (record) => {
      return {
        onClick: () => {
          currentBuildingId.value = record.id ? record.id : 0;
          currentBuildingVillageId.value = record.village_id
            ? record.village_id
            : 0;
          currentBuildingroomId.value = record.room_number
            ? record.room_number
            : 0;
          console.log("有数据没", record);
          console.log(record.room_number);
          roomDetail.value = record;
          houseResourceVisible.value = true;
        },
      };
    };
    //搜索
    let serchList = "";
    const onSearch = (searchValue) => {
      page.value = 1;
      limit.value = 20;
      gethouseList();
    };

    // 导入房源
    // 导入房源
    const visibleImport = ref(false);
    const btnImport = () => {
      console.log("111");
      visibleImport.value = true;
    };
    // 关闭房源
    const btnClear = () => {
      visibleImport.value = false;
    };
    const refreshList = () => {
      gethouseList();
    };

    // 搜索房源标签
    const optionsTag = ref([]);
    const selectTagValue = ref(undefined);
    const placeholderTag = computed(() => {
      return `请搜索${BLCOMMON.utils.L("房源")}标签`;
    });
    const getTagList = () => {
      request.get("/org", "/manage/taglib/house/all").then((res) => {
        optionsTag.value = res.list.map((item) => {
          return {
            value: item.id,
            label: item.name,
          };
        });
      });
    };
    const handleSearch = (selectedKeys, confirm, dataIndex) => {
      page.value = 1;
      limit.value = 20;
      confirm();
      gethouseList();
    };
    const handleReset = (clearFilters) => {
      clearFilters();
    };

    const init = () => {
      gethouseList();
      getTagList();
    };
    init();

    // 导出
    const btnExport = () => {
      let params = {
        page: page.value,
        pageSize: limit.value,
        is_export: 1,
      };

      if (
        filtersList.value.village_name &&
        filtersList.value.village_name.length > 0
      ) {
        params.village_id = filtersList.value.village_name.join(",");
      }

      if (
        filtersList.value.build_name &&
        filtersList.value.build_name.length > 0
      ) {
        params.build_id = filtersList.value.build_name.join(",");
      }

      if (state.filterTagId) {
        params.tag_id = state.filterTagId;
      }

      if (keywordsValue.value) {
        params.keywords = keywordsValue.value;
      }

      if (state.activeKey == "invitation") {
        params.invitation_status = 1;
      }

      request
        .get("/village", "/houseResource/resourceList", { ...params })
        .then((res) => {
          if (res.result && res.result.fileUrl) {
            let info = {
              type: "selectDownloadFiles",
              url: res.result.fileUrl,
            };
            window.microApp.forceDispatch(info);
          }
        });
    };

    return {
      clearList,
      ...toRefs(state),
      handleClose,
      columns,
      rowSelection,
      buildingEditVisible,
      houseResourceVisible,
      pagination,
      houseList,
      currentBuildingId,
      currentBuildingVillageId,
      currentBuildingroomId,
      buildingEdit,
      handleTableChange,
      Rowclick,
      handleBuildingClose,
      handleBuildingSuccess,
      houseDetails,
      roomDetail,
      houseResourceClose,
      houseResourceSuccess,
      gethouseList,
      keywordsValue,
      onSearch,
      visibleImport,
      btnImport,
      btnClear,
      refreshList,
      loading,
      handleSearch,
      handleReset,
      optionsTag,
      placeholderTag,
      selectTagValue,

      btnExport,
    };
  },
});
</script>

<style lang="less" scoped>
.input-class {
  width: 200px;
}
.input-width {
  width: 160px;
}
:deep(.ant-table-filter-trigger) {
  padding: 0 8px;
}
</style>
